import React, { useState, useRef, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import { NavBar, Input, Button, Toast } from 'antd-mobile';
import { LeftOutline, SendOutline } from 'antd-mobile-icons';
import styles from './AIChat.module.css';
import { aiService, AIServiceError, AI_ERRORS } from './services/aiService';

function AIChat() {
  const navigate = useNavigate();
  const [messages, setMessages] = useState([
    {
      id: 1,
      type: 'ai',
      content: '你好！我是智能助手，有什么可以帮助你的吗？',
      timestamp: new Date()
    }
  ]);
  const [inputText, setInputText] = useState('');
  const [loading, setLoading] = useState(false);
  const messagesEndRef = useRef(null);

  // 自动滚动到底部
  const scrollToBottom = () => {
    messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' });
  };

  useEffect(() => {
    scrollToBottom();
  }, [messages]);

  // 错误处理函数
  const handleAIError = (error) => {
    let message = '发送失败，请重试';

    if (error instanceof AIServiceError) {
      switch (error.type) {
        case AI_ERRORS.NETWORK_ERROR:
          message = '网络连接失败，请检查网络后重试';
          break;
        case AI_ERRORS.API_KEY_INVALID:
          message = 'AI 服务暂时不可用，请稍后重试';
          break;
        case AI_ERRORS.RATE_LIMIT:
          message = '请求过于频繁，请稍后重试';
          break;
        case AI_ERRORS.SERVER_ERROR:
          message = '服务器暂时不可用，请稍后重试';
          break;
        default:
          message = '发生未知错误，请重试';
      }
    }

    Toast.show({
      content: message,
      icon: 'fail',
      duration: 3000
    });
  };

  // 发送消息
  const sendMessage = async () => {
    if (!inputText.trim() || loading) return;

    const userMessage = inputText.trim();
    const newUserMessage = {
      id: Date.now(),
      type: 'user',
      content: userMessage,
      timestamp: new Date()
    };

    // 添加用户消息
    setMessages(prev => [...prev, newUserMessage]);
    setInputText('');
    setLoading(true);

        try {
      // 调用 AI 服务
      const result = await aiService.sendMessage(userMessage);
      
      if (result.success) {
        const newAIMessage = {
          id: Date.now() + 1,
          type: 'ai',
          content: result.data.reply,
          timestamp: new Date()
        };

        setMessages(prev => [...prev, newAIMessage]);
      } else {
        throw new Error('AI 服务返回失败');
      }
    } catch (error) {
      console.error('发送消息失败:', error);
      handleAIError(error);
    } finally {
      setLoading(false);
    }
  };

  // 处理回车发送
  const handleKeyPress = (e) => {
    if (e.key === 'Enter' && !e.shiftKey) {
      e.preventDefault();
      sendMessage();
    }
  };

  const handleBack = () => {
    navigate(-1);
  };

  // 格式化时间
  const formatTime = (timestamp) => {
    return timestamp.toLocaleTimeString('zh-CN', {
      hour: '2-digit',
      minute: '2-digit'
    });
  };

  return (
    <div className={styles.container}>
      {/* 导航栏 */}
      <NavBar
        onBack={handleBack}
        backIcon={<LeftOutline />}
        className={styles.navbar}
      >
        AI 智能助手
      </NavBar>

      {/* 消息列表 */}
      <div className={styles.messageContainer}>
        <div className={styles.messageList}>
          {messages.map((message) => (
            <div
              key={message.id}
              className={`${styles.messageItem} ${styles[message.type]}`}
            >
              <div className={styles.messageAvatar}>
                {message.type === 'user' ? '👤' : '🤖'}
              </div>
              <div className={styles.messageContent}>
                <div className={styles.messageBubble}>
                  {message.content}
                </div>
                <div className={styles.messageTime}>
                  {formatTime(message.timestamp)}
                </div>
              </div>
            </div>
          ))}

          {/* 加载指示器 */}
          {loading && (
            <div className={`${styles.messageItem} ${styles.ai}`}>
              <div className={styles.messageAvatar}>🤖</div>
              <div className={styles.messageContent}>
                <div className={styles.messageBubble}>
                  <div className={styles.typingIndicator}>
                    <span></span>
                    <span></span>
                    <span></span>
                  </div>
                </div>
              </div>
            </div>
          )}

          <div ref={messagesEndRef} />
        </div>
      </div>

      {/* 输入区域 */}
      <div className={styles.inputArea}>
        <div className={styles.inputWrapper}>
          <Input
            value={inputText}
            onChange={setInputText}
            onKeyPress={handleKeyPress}
            placeholder="请输入消息..."
            className={styles.messageInput}
            maxLength={500}
          />
          <Button
            color="primary"
            size="small"
            className={styles.sendButton}
            onClick={sendMessage}
            disabled={!inputText.trim() || loading}
          >
            <SendOutline />
          </Button>
        </div>
      </div>
    </div>
  );
}

export default AIChat; 